<template>
  <div class="attendance-record-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">考勤记录管理</span>
          <div class="right-button">
            <!-- 新增按钮已隐藏
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增记录
            </el-button>
            -->
            <el-button type="info" @click="handleImport">
              <el-icon><Upload /></el-icon>导入
            </el-button>
            <el-button type="warning" @click="handleExport">
              <el-icon><Download /></el-icon>导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="员工姓名" prop="employeeName">
          <el-select
            v-model="queryParams.employeeId"
            placeholder="请选择员工姓名"
            clearable
            filterable
            remote
            :remote-method="searchEmployees"
            :loading="employeeLoading"
            style="width: 200px"
            :reserve-keyword="false"
            :default-first-option="true"
            @change="handleQuery"
          >
            <el-option
              v-for="item in employeeOptions"
              :key="item.employeeId"
              :label="item.employeeName"
              :value="item.employeeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考勤日期" prop="attendanceDate">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="考勤状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="考勤状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="option in STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="recordList" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="recordId" label="记录编号" align="center" width="100" />
        <el-table-column prop="employeeName" label="员工姓名" align="center" width="120" />
        <el-table-column prop="attendanceDate" label="考勤日期" align="center" width="120" />
        <el-table-column prop="clockInTime" label="上班打卡" align="center" width="180">
          <template #default="scope">
            {{ scope.row.clockInTime ? formatDateTime(scope.row.clockInTime) : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="clockInAddress" label="上班地点" align="center" width="250">
          <template #default="scope">
            {{ scope.row.clockInAddress || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="clockOutTime" label="下班打卡" align="center" width="180">
          <template #default="scope">
            {{ scope.row.clockOutTime ? formatDateTime(scope.row.clockOutTime) : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="clockOutAddress" label="下班地点" align="center" width="250">
          <template #default="scope">
            {{ scope.row.clockOutAddress || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="考勤状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ruleName" label="考勤规则" align="center" width="120" />
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <!-- 编辑按钮已隐藏
            <el-button
              link
              type="primary"
              size="small"
              @click="handleUpdate(scope.row)"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            -->
            <el-button link type="primary" size="small" @click="handleView(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-popconfirm :title="`是否确认删除该考勤记录?`" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button link type="danger" size="small">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 考勤记录表单组件 -->
    <AttendanceRecordForm
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :record="form"
      @success="getList"
    />

    <!-- 考勤记录详情组件 -->
    <AttendanceRecordDetail v-if="detailVisible" v-model="detailVisible" :record="currentRecord" />

    <!-- 导入对话框 -->
    <el-dialog title="导入考勤记录" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, FormInstance, UploadInstance } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  View,
  Delete,
  Upload,
  Download
} from "@element-plus/icons-vue";
import type {
  AttendanceRecordQuery,
  AttendanceRecordVO,
  AttendanceStatus
} from "@/types/attendance/record";
import { STATUS_OPTIONS, STATUS_LABEL_MAP, STATUS_TYPE_MAP } from "@/types/attendance/record";
import {
  getAttendanceRecordList,
  deleteAttendanceRecord,
  exportAttendanceRecord,
  downloadImportTemplate
} from "@/api/attendance/record";
import { useUserStore } from "@/store/modules/user";
import { getPersonnelList } from "@/api/attendance/personnel";
import AttendanceRecordForm from "./components/AttendanceRecordForm.vue";
import AttendanceRecordDetail from "./components/AttendanceRecordDetail.vue";

// 查询参数
const queryParams = reactive<AttendanceRecordQuery>({
  pageNum: 1,
  pageSize: 10,
  employeeName: "",
  employeeId: undefined,
  status: undefined
});

// 日期范围
const dateRange = ref<[string, string]>(["", ""]);

// 加载状态
const loading = ref(false);
// 总条数
const total = ref(0);
// 考勤记录列表
const recordList = ref<AttendanceRecordVO[]>([]);
// 查询表单ref
const queryRef = ref<FormInstance>();
// 上传ref
const uploadRef = ref<UploadInstance>();

// 员工选项
const employeeOptions = ref<Array<{ employeeId: number; employeeName: string }>>([]);
// 员工加载状态
const employeeLoading = ref(false);

// 弹窗控制
const dialog = reactive({
  visible: false,
  title: ""
});
// 详情弹窗控制
const detailVisible = ref(false);
// 当前记录
const currentRecord = ref<AttendanceRecordVO>();
// 表单数据
const form = ref<AttendanceRecordVO>();

// 上传相关
const upload = reactive({
  open: false,
  isUploading: false,
  headers: { Authorization: "Bearer " + useUserStore().token },
  url: import.meta.env.VITE_APP_BASE_API + "/attendance/record/import"
});

// 获取考勤状态标签
const getStatusLabel = (status: any) => {
  // 确保状态值是字符串类型
  const statusStr = String(status);
  console.log("状态值:", status, "类型:", typeof status);
  return STATUS_LABEL_MAP[statusStr as AttendanceStatus] || "未知";
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return "-";
  try {
    // 将ISO字符串转换为本地日期时间格式
    const date = new Date(dateTimeStr);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false
    });
  } catch (e) {
    console.error("日期格式化错误:", e);
    return dateTimeStr;
  }
};

// 获取考勤状态类型
const getStatusType = (status: any): "success" | "warning" | "danger" | "info" => {
  // 确保状态值是字符串类型
  const statusStr = String(status);
  return STATUS_TYPE_MAP[statusStr as AttendanceStatus] || "info";
};

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const [startDate, endDate] = dateRange.value;
    // 创建新的查询参数对象，避免修改原始对象
    const params: any = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    };

    // 添加日期参数，确保格式正确
    if (startDate) {
      params.startDate = formatQueryDate(startDate);
      console.log("格式化后的开始日期:", params.startDate);
    }

    if (endDate) {
      params.endDate = formatQueryDate(endDate);
      console.log("格式化后的结束日期:", params.endDate);
    }

    // 如果有employeeId，使用精确查询
    if (queryParams.employeeId) {
      params.employeeId = queryParams.employeeId;
      // 不再传递employeeName，避免条件冲突
    } else if (queryParams.employeeName) {
      // 仅当没有employeeId但有employeeName时使用
      params.employeeName = queryParams.employeeName;
    }

    // 仅当status有值时添加到查询参数
    if (queryParams.status) {
      params.status = queryParams.status;
    }

    console.log("查询参数:", params);
    const res = await getAttendanceRecordList(params);
    recordList.value = res.data.rows;
    total.value = res.data.total;

    // 添加调试信息
    if (recordList.value && recordList.value.length > 0) {
      console.log("查询结果数量:", recordList.value.length);
      console.log("首条记录数据:", recordList.value[0]);
    } else {
      console.log("没有记录数据");
    }
  } catch (error) {
    console.error("获取考勤记录列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理日期格式
const formatQueryDate = (dateStr: string) => {
  if (!dateStr) return undefined;

  // 确保日期格式符合后端要求 (yyyy-MM-dd)
  try {
    // 简单验证日期格式
    const regex = /^\d{4}-\d{2}-\d{2}$/;
    if (!regex.test(dateStr)) {
      console.error("日期格式错误:", dateStr);
      return undefined;
    }

    // 手动处理日期字符串，避免使用Date对象的潜在问题
    // 直接传递原始格式化字符串，确保YYYY-MM-DD转换为后端期望的格式
    // 这里不做额外处理，仅返回验证后的日期字符串
    return dateStr;
  } catch (e) {
    console.error("日期处理错误:", e);
    return undefined;
  }
};

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1;

  // 如果选择了employeeId，找到对应的员工名称
  if (queryParams.employeeId) {
    const selectedEmployee = employeeOptions.value.find(
      item => item.employeeId === queryParams.employeeId
    );
    if (selectedEmployee) {
      queryParams.employeeName = selectedEmployee.employeeName;
    }
  } else {
    queryParams.employeeName = "";
  }

  getList();
};

// 重置操作
const resetQuery = () => {
  queryRef.value?.resetFields();
  dateRange.value = ["", ""];
  queryParams.employeeId = undefined;
  queryParams.employeeName = "";
  queryParams.status = undefined;
  getInitialEmployees(); // 重置后重新获取员工列表
  handleQuery();
};

// 新增操作
const handleAdd = () => {
  dialog.title = "新增考勤记录";
  dialog.visible = true;
  form.value = undefined;
};

// 修改操作
const handleUpdate = (row: AttendanceRecordVO) => {
  dialog.title = "修改考勤记录";
  dialog.visible = true;
  form.value = { ...row };
};

// 查看操作
const handleView = (row: AttendanceRecordVO) => {
  detailVisible.value = true;
  currentRecord.value = row;
};

// 删除操作
const handleDelete = async (row: AttendanceRecordVO) => {
  try {
    await deleteAttendanceRecord(row.recordId);
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error("删除考勤记录失败:", error);
  }
};

// 导出操作
const handleExport = async () => {
  const [startDate, endDate] = dateRange.value;
  // 创建新的导出参数对象
  const params: any = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize
  };

  // 添加日期参数，确保格式正确
  if (startDate) {
    params.startDate = formatQueryDate(startDate);
    console.log("导出 - 格式化后的开始日期:", params.startDate);
  }

  if (endDate) {
    params.endDate = formatQueryDate(endDate);
    console.log("导出 - 格式化后的结束日期:", params.endDate);
  }

  // 如果有employeeId，使用精确查询
  if (queryParams.employeeId) {
    params.employeeId = queryParams.employeeId;
  } else if (queryParams.employeeName) {
    params.employeeName = queryParams.employeeName;
  }

  // 仅当status有值时添加到查询参数
  if (queryParams.status) {
    params.status = queryParams.status;
  }

  try {
    await exportAttendanceRecord(params);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出考勤记录失败:", error);
  }
};

// 导入操作
const handleImport = () => {
  upload.open = true;
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    await downloadImportTemplate();
    ElMessage.success("下载成功");
  } catch (error) {
    console.error("下载模板失败:", error);
  }
};

// 文件上传中处理
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 文件上传成功处理
const handleFileSuccess = () => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();
  getList();
  ElMessage.success("导入成功");
};

// 提交上传文件
const submitFileForm = () => {
  uploadRef.value?.submit();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

// 搜索员工
const searchEmployees = async (query: string) => {
  if (query && query.length > 1) {
    // 至少输入2个字符才开始搜索
    employeeLoading.value = true;
    try {
      const res = await getPersonnelList({
        pageNum: 1,
        pageSize: 20,
        personnelName: query
      });
      employeeOptions.value = res.data.rows.map((item: any) => ({
        employeeId: item.personnelId,
        employeeName: item.personnelName
      }));
    } catch (error) {
      console.error("获取员工列表失败:", error);
      employeeOptions.value = [];
    } finally {
      employeeLoading.value = false;
    }
  } else if (query.length === 0) {
    // 如果用户清空了搜索框，重新获取初始列表
    getInitialEmployees();
  } else {
    // 输入字符不足，不执行搜索
    employeeOptions.value = [];
  }
};

// 初始获取员工列表
const getInitialEmployees = async () => {
  employeeLoading.value = true;
  try {
    const res = await getPersonnelList({
      pageNum: 1,
      pageSize: 20
    });
    employeeOptions.value = res.data.rows.map((item: any) => ({
      employeeId: item.personnelId,
      employeeName: item.personnelName
    }));
  } catch (error) {
    console.error("获取初始员工列表失败:", error);
  } finally {
    employeeLoading.value = false;
  }
};

// 监听日期范围变化
const handleDateRangeChange = (val: [string, string] | null) => {
  console.log("日期范围变化原始值:", val);

  if (val && Array.isArray(val) && val.length === 2) {
    dateRange.value = val;
    console.log("设置日期范围为:", dateRange.value);
  } else {
    dateRange.value = ["", ""];
    console.log("重置日期范围");
  }
};

// 初始化
onMounted(() => {
  getList();
  getInitialEmployees();
});
</script>

<style lang="scss" scoped>
.attendance-record-container {
  padding: 0px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
    }

    .right-button {
      display: flex;
      gap: 10px;
    }
  }

  :deep(.el-card__header) {
    padding: 10px 20px;
  }

  .el-pagination {
    margin-top: 15px;
    justify-content: flex-end;
  }

  .empty-block {
    text-align: center;
    padding: 20px 0;

    .empty-tips {
      margin-top: 10px;
      color: #909399;
    }
  }
}
</style>
